package bom.example.common.sql;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表结构建造器
 */
public class TableGenerator {

    //-1小写,1大写
    public static final int format = -1;
    /**
     * 用来存储Java等属性类型与sql中属性类型的对照
     * </br>
     * 例如：java.lang.Integer 对应 integer
     */
    public static Map<String, String> map = new HashMap<>();

    static {
        map.put("boolean", "tinyint(1)");
        map.put("int", "int");
        map.put("short", "int");
        map.put("long", "bigint");
        map.put("float", "float");
        map.put("double", "double");
        map.put("char", "varchar(255)");
        map.put("java.lang.String", "varchar(255)");
        map.put("java.lang.Integer", "int");
        map.put("java.lang.byte[]", "blob");
        map.put("java.lang.Boolean", "bit");
        map.put("java.lang.Long", "integer unsigned");
        map.put("java.math.BigInteger", "bigint unsigned");
        map.put("java.lang.Float", "float");
        map.put("java.lang.Double", "float");
        map.put("java.sql.Date", "datetime");
        map.put("java.sql.Time", "time");
        map.put("java.sql.Timestamp", "datetime");
        map.put("java.util.Date", "datetime");
        map.put("java.lang.Byte", "tinyint");
    }

    public static void main(String[] args) {

    //    System.out.println(str);
    }



    /**
     * 根据实体类生成建表语句
     *
     * @param
     * @return
     */
    public static String generateSql(Class clz) {
        String className = clz.getSimpleName();
        // 表表名adminUser → tb_admin_user
        className = "tb_" + getStandardFields(className).toLowerCase();
        Field[] fields = clz.getDeclaredFields();
        StringBuffer column = new StringBuffer();
        String varchar = " CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,";
        for (Field f : fields) {
            System.out.println(f.getType().getName());
            String typeName = f.getType().getName();
            if (f.getName().equals("serialVersionUID")) {
                continue;
            }
            if ("java.lang.String".equals(typeName)) {
                column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(typeName)).append(varchar);
            } else {
                column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(typeName)).append(",");
            }
        }
        StringBuffer sql = new StringBuffer();
        sql.append("\n DROP TABLE IF EXISTS `" + className + "`; ")
                .append(" \n CREATE TABLE `" + className + "`  (")
                .append(" \n `bind_id` int(11) NOT NULL AUTO_INCREMENT,")
                .append(column)
                .append(" `create_time` datetime NULL DEFAULT NULL,\n" +
                        "  `update_time` datetime NULL DEFAULT NULL,\n" +
                        "  `deleted` bit(1) NULL DEFAULT NULL,\n" +
                        "  `version` int(11) NULL DEFAULT NULL,\n" +
                        "  `create_user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,\n" +
                        "  `update_user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,")
                .append(" \n PRIMARY KEY (`bind_id`) USING BTREE,")
                .append("\n INDEX `id`(`bind_id`) USING BTREE")
                .append(" \n ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;\n");
        return sql.toString();

    }

    /**
     * 转换为标准等sql字段 例如 adminUser → admin_user
     *
     * @param str 转换为字符串的字段名
     * @return
     */
    public static String getStandardFields(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i != 0 && (c > 'A' && c < 'Z')) {
                sb.append("_");
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 获取包下面等所有实体类名称，类似于获取 XXX.java
     *
     * @param packageName 全类名
     * @return
     */
    public static List<String> getAllClasses(String packageName) {
        List<String> classList = new ArrayList<>();
        String className = "";
        File f = new File(packageName);
        if (f.exists() && f.isDirectory()) {
            File[] files = f.listFiles();
            // 遍历实体类下面等所有.java文件 获取其类名
            for (File file : files) {
                className = file.getName();
                classList.add(className);
            }
            return classList;
        } else {
            return null;
        }
    }


}
